package com.bcbim.api_web.user.controller;

import com.bcbim.authentication_interface.user.dao.UserDAO;
import com.bcbim.authentication_interface.user.dao.UserRoleDAO;
import com.bcbim.authentication_interface.user.dto.PasswordUpdateDTO;
import com.bcbim.authentication_interface.user.dto.UserListDTO;
import com.bcbim.authentication_interface.user.dto.UserRoleDTO;
import com.bcbim.authentication_interface.user.service.UserService;
import com.bcbim.authentication_interface.user.vo.UserVO;
import com.bcbim.authentication_interface.util.AuthUtil;
import com.bcbim.common.log.annotation.RecordLog;
import com.bcbim.common.response.annotation.Translate;
import com.bcbim.common.response.vo.ReturnMsg;
import com.bcbim.common.response.vo.ReturnPageMsg;
import com.bcbim.common.sys.Code;
import com.bcbim.common.sys.Constant;
import com.bcbim.common.sys.ParamException;
import com.bcbim.common.util.AESUtil;
import com.bcbim.common.util.GuidUtil;
import com.bcbim.common.util.ParamCheck;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 用户管理
 * @Author: ye
 * @Date: 2020/11/30
 * @Version: V1.0
 **/
@RestController
@RequestMapping("/user")
public class UserManagementController {

    @Reference(protocol = "dubbo", group = "authentication", version = "1.0.0")
    private UserService userServiceImpl;

    /**
     * @Description: 用户列表
     * @Param: UserQuery
     * @Return: ReturnPageMsg
     * @Author: ye
     * @Date: 2020/11/30
     */
    @Translate
    @RecordLog(content = "获取用户列表")
    @PostMapping("listUser")
    public ReturnPageMsg listUser(UserListDTO userListDTO) {
        try {
            ParamCheck.pageNumCheck(userListDTO.getPageNum(), userListDTO.getPageSize());
        } catch (ParamException e) {
            return ReturnPageMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        userListDTO.setStart((userListDTO.getPageNum() - 1) * userListDTO.getPageSize());
        userListDTO.setDel(Constant.NOT_DEL);
        List<UserVO> list = new ArrayList<>();
        int total = userServiceImpl.listUserCount(userListDTO);
        if (total == 0) {
            return ReturnPageMsg.consSuccess(total, list);
        }
        list = userServiceImpl.listUser(userListDTO);
        return ReturnPageMsg.consSuccess(total, list);
    }

    /**
     * @Description: 新建用户
     * @Param: UserDO
     * @Return: ReturnMsg
     * @Author: ye
     * @Date: 2020/11/30
     */
    @RecordLog(content = "新建用户")
    @PostMapping("saveUser")
    public ReturnMsg saveUser(UserDAO userDAO) {
        try {
            ParamCheck.stringNotNullLengthCheck(20, userDAO.getUsername());
            ParamCheck.stringNotNullLengthCheck(15, userDAO.getPassword());
            ParamCheck.stringCanBeNullLengthCheck(20, userDAO.getNickname());
            ParamCheck.stringCanBeNullLengthCheck(20, userDAO.getPhone());
            ParamCheck.flagCheck(userDAO.getEnable());
            if (userServiceImpl.usernameCheck(userDAO.getUsername()) > 0) {
                return ReturnMsg.consFail("用户名已存在");
            }
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        userDAO.setId(GuidUtil.get());
        userDAO.setPassword(AESUtil.encrypt(userDAO.getPassword()));
        userDAO.setCreateBy(Objects.requireNonNull(AuthUtil.getUserIdDecrypt()));
        userDAO.setCreateTime(LocalDateTime.now());
        userDAO.setDel(Constant.NOT_DEL);
        int result = userServiceImpl.saveUser(userDAO);
        return result == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * @Description: 删除用户
     * @Param: usernames
     * @Return: ReturnMsg
     * @Author: ye
     * @Date: 2020/11/30
     */
    @RecordLog(content = "删除用户")
    @PostMapping("removeUser")
    public ReturnMsg removeUser(String id) {
        try {
            ParamCheck.idCheck(id);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        int result = userServiceImpl.removeUser(id, Constant.DEL);
        return result == 1 ? ReturnMsg.consSuccess(Constant.DEL_SUCCESS) : ReturnMsg.consFail(Constant.DEL_FAIL);
    }

    /**
     * @Description: 编辑更新用户
     * @Param: UserDO
     * @Return: ReturnMsg
     * @Author: ye
     * @Date: 2020/11/30
     */
    @RecordLog(content = "编辑用户信息")
    @PostMapping("updateUser")
    public ReturnMsg updateUser(UserDAO userDAO) {
        try {
            ParamCheck.idCheck(userDAO.getId());
            ParamCheck.stringNotNullLengthCheck(20, userDAO.getUsername());
            ParamCheck.stringCanBeNullLengthCheck(20, userDAO.getNickname());
            ParamCheck.stringCanBeNullLengthCheck(20, userDAO.getPhone());
            ParamCheck.flagCheck(userDAO.getEnable());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        userDAO.setUpdateBy(Objects.requireNonNull(AuthUtil.getUserIdDecrypt()));
        userDAO.setUpdateTime(LocalDateTime.now());
        int result = userServiceImpl.updateUser(userDAO);
        return result == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * @Description: 保存用户角色
     * @Param: SaveUserRoleQuery
     * @Return: ReturnMsg
     * @Author: ye
     * @Date: 2021/7/6
     */
    @PostMapping("/saveUserRole")
    public ReturnMsg saveUserRole(UserRoleDTO userRoleDTO) {
        //参数校验
        try {
            ParamCheck.idCheck(userRoleDTO.getUserId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        List<UserRoleDAO> list = new ArrayList<>();
        if (userRoleDTO.getArrayRoleId() == null || userRoleDTO.getArrayRoleId().length == 0) {
            return ReturnMsg.consFail("权限设置不能为空，请重新选择。");
        }
        if (ObjectUtils.isNotEmpty(userRoleDTO) && userRoleDTO.getArrayRoleId().length > 0) {
            for (String roleId : userRoleDTO.getArrayRoleId()) {
                UserRoleDAO userRoleDAO = new UserRoleDAO();
                try {
                    ParamCheck.idCheck(roleId);
                } catch (ParamException e) {
                    return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
                }
                userRoleDAO.setId(GuidUtil.get());
                userRoleDAO.setRoleId(roleId);
                userRoleDAO.setUserId(userRoleDTO.getUserId());
                list.add(userRoleDAO);
            }
        }
        //清除用户角色
        userServiceImpl.clearUserRole(userRoleDTO.getUserId());
        //保存用户角色
        userServiceImpl.saveUserRole(list);
        return ReturnMsg.consSuccess(Constant.SAVE_SUCCESS);
    }

    /**
     * @return ReturnMsg
     * @Description 查询角色
     * @Author XueHao
     * @Date 2021/8/23
     */
    @PostMapping("/selectRole")
    public ReturnMsg selectRole(String roleName) {
        List<Code> list = userServiceImpl.selectRole(roleName);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * 重置密码
     *
     * @param id id
     * @return ReturnMsg
     * @author XueHao
     * @date 2021/12/2
     */
    @PostMapping("/resetPassword")
    public ReturnMsg resetPassword(String id) {
        //参数校验
        try {
            ParamCheck.idCheck(id);
        } catch (ParamException e) {
            return ReturnMsg.consSuccess(ParamException.PARAMETER_ERROR);
        }
        //重置密码并加密
        String password = AESUtil.encrypt(Constant.RESET_PASSWORD);
        int result = userServiceImpl.resetPassword(id, password);
        return result == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);

    }

    /**
     * 查询用户详情
     *
     * @param id id
     * @return ReturnMsg
     * @author XueHao
     * @date 2022/1/14
     */
    @PostMapping("/getUser")
    public ReturnMsg getUser(String id) {
        try {
            ParamCheck.idCheck(id);
        } catch (ParamException e) {
            return ReturnMsg.consSuccess(ParamException.PARAMETER_ERROR);
        }
        UserVO userVO = userServiceImpl.getUser(id);
        return ReturnMsg.consSuccess(userVO);
    }

    /**
     * 修改密码
     *
     * @param passwordUpdateDTO
     * @author xuehao
     * @createDate 2022/3/16 13:52
     * @retuen ReturnMsg
     */
    @PostMapping("/updatePassword")
    public ReturnMsg updatePassword(PasswordUpdateDTO passwordUpdateDTO) {
        try {
            ParamCheck.stringNotEmpty(passwordUpdateDTO.getOldPassword(), 50);
            ParamCheck.stringNotEmpty(passwordUpdateDTO.getNewPassword(), 50);
            ParamCheck.stringNotEmpty(passwordUpdateDTO.getAffirmPassword(), 50);
        } catch (ParamException e) {
            return ReturnMsg.consSuccess(ParamException.PARAMETER_ERROR);
        }
        //判断旧密码是否正确
        String id = AuthUtil.getUserIdDecrypt();
        String oldPassword = AESUtil.encrypt(passwordUpdateDTO.getOldPassword());
        if (userServiceImpl.checkOldPassword(id, oldPassword) != 1) {
            return ReturnMsg.consFail("原始密码错误!");
        }
        //判断新密码和确认密码是否相同
        if (!StringUtils.equals(passwordUpdateDTO.getNewPassword(), passwordUpdateDTO.getAffirmPassword())) {
            return ReturnMsg.consFail("两次输入密码不一致!");
        }
        //更改密码
        String newPassword = AESUtil.encrypt(passwordUpdateDTO.getNewPassword());
        UserDAO userDAO = new UserDAO();
        userDAO.setUpdateBy(id);
        userDAO.setUpdateTime(LocalDateTime.now());
        userDAO.setPassword(newPassword);
        userDAO.setId(id);
        int result = userServiceImpl.updateUser(userDAO);
        return result == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 查询用户拥有的平台
     *
     * @author xuehao
     * @createDate 2022/3/18 9:38
     * @retuen String
     */
    @PostMapping("/getApplicationPlatform")
    public ReturnMsg getApplicationPlatform() {
        String userId = AuthUtil.getUserIdDecrypt();
        //查询用户拥有的平台
        List<Code> list = userServiceImpl.selectApplicationPlatformByUserId(userId);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * @return ReturnMsg
     * @Description 查询用户角色
     * @Author XueHao
     * @Date 2021/8/25
     */
    @PostMapping("getUserRole")
    public ReturnMsg getUserRole(String userId) {
        List<Code> arrayUserId = userServiceImpl.getUserRole(userId);
        return ReturnMsg.consSuccess(arrayUserId);
    }
}
